package org.gdufe.comment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.gdufe.comment.mapper.CommentMapper;
import org.gdufe.comment.service.CommentService;
import org.gdufe.pojos.dto.CreateCommentDto;
import org.gdufe.pojos.dto.PageParams;
import org.gdufe.pojos.pojo.BookCollection;
import org.gdufe.pojos.pojo.Comment;
import org.gdufe.pojos.vo.PageResponseResult;
import org.gdufe.pojos.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ComentServiceImpl implements CommentService {
    @Autowired
    private CommentMapper commentMapper;

    @Override
    public PageResponseResult querry(PageParams pageParams, Integer bId) {
        if (pageParams==null||pageParams.getPageNo()<=0||pageParams.getPageSize()<=0){
            pageParams=new PageParams();
        }
        QueryWrapper<Comment> wrapper=new QueryWrapper<>();
        wrapper.eq("b_id",bId);
        //分页对象
        Page<Comment> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        IPage<Comment> pageResult = commentMapper.selectPage(page,wrapper);
        List<Comment> records = pageResult.getRecords();
        // 获取数据总数
        long total = pageResult.getTotal();
        // 构建结果集
        PageResponseResult result=new PageResponseResult((int) pageResult.getCurrent(), (int) pageResult.getSize(), (int) pageResult.getTotal());
        result.setData(records);
        return result;
    }

    @Override
    public R createComment(CreateCommentDto dto, String username) {
        Comment comment=new Comment();
        Integer bId = dto.getBId();
        Double point = dto.getPoint();
        String content = dto.getContent();
        if (bId==null||bId<=0||point==null||point<0||point>10||content==null||content.isEmpty()){
            return R.errorResult(500,"参数错误");
        }
        comment.setBId(bId);
        comment.setPoint(point);
        comment.setUsername(username);
        comment.setContent(content);
        int i = commentMapper.insert(comment);
        if (i<=0){
            return R.errorResult(500,"评论失败");
        }
        return R.okResult(200,"评论成功");
    }

    @Override
    public R querryPoint(Integer bId) {
        QueryWrapper<Comment> wrapper=new QueryWrapper<>();
        wrapper.eq("b_id",bId);
        List<Comment> comments = commentMapper.selectList(wrapper);

        //计算平均值
        double point = comments.stream().mapToDouble(Comment::getPoint).average().orElse(10.0);
        return R.okResult(point);
    }
}
